﻿<template>
  <div>
    <el-form :model="queryCondition" ref="refQueryCondition" label-width="auto" style="width:100%;">
      <el-row>
        <el-col :span="6">
          <el-form-item label="用户名:" prop="name">
            <el-input v-model="queryCondition.name" autocomplete="off" prefix-icon="el-icon-search" placeholder="请输入内容"
              @keyup.enter.native="loadUserList()" />
          </el-form-item>
        </el-col>

        <el-col :span="7" v-if="isHeadOffice">
          <el-form-item label="所属单位:" prop="ownCompany">
            <el-select v-model="queryCondition.companyId" placeholder="请选择" clearable>
              <el-option v-for="item in companyList" :key="item.id" :label="item.shortName" :value="item.id">
                <span style="float: left;padding-right: 20px;">{{ item.shortName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="6">-->
        <!--          <el-form-item label="用户角色:" prop="type">-->
        <!--            <el-select filterable default-first-option placeholder="请选择" v-model="queryCondition.roleId">-->
        <!--              <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <el-col :span="5">
          <el-button type="primary" style="margin-left:10px;" @click="loadUserList()">查询</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-table v-loading="isLoading" :data="userList" :key="'user_list_'+type" tooltip-effect="dark"
      @row-click="handleClickRow" style="width: 100%">


      <el-table-column key="index" label='序号' type="index" width="55">
      </el-table-column>
      <el-table-column prop="loginName" label="登录名" width="200" align="left" />
      <el-table-column prop="name" show-overflow-tooltip label="姓名" />
      <el-table-column prop="name" show-overflow-tooltip label="岗位">
        <template slot-scope="scope">
          <span v-if="!scope.row.roleList||scope.row.roleList.length==0">无</span>
          <div v-else>
            <el-tag v-for="item in scope.row.roleList">
              {{item.name}}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="归属公司">
        <template slot-scope="item">{{companyMap[item.row.companyId]?companyMap[item.row.companyId].name:''}}</template>
      </el-table-column>
      <el-table-column key="option" align="center" width="250" label="操作">
        <template slot-scope="item">
          <el-button v-if="checkPermission('sys_user:update')" type="success" size="mini"
            @click="openEditDlg(item.row)">模型权限
          </el-button>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="text-align:center;padding-top:10px;" :current-page="pageNo" background
      layout="prev, pager, next" :total="dataCount" @current-change="loadUserList"></el-pagination>

    <el-dialog v-loading="modelList.editMode&&loadingModel" :title=" '模型列表'" :visible.sync="modelDlgVisible"
      :close-on-click-modal="false" width="70%">

      <el-form :model="queryModelCondition" ref="refQueryModelCondition" label-width="auto" style="width:100%;">
        <el-row>
          <el-col :span="6">
            <el-form-item label="模型名称:" prop="name">
              <el-input v-model="queryModelCondition.name" autocomplete="off" prefix-icon="el-icon-search"
                placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="适用项目类型:" prop="type">
              <meta-select v-model="queryModelCondition.projectType" type="product-type"></meta-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-button type="primary" style="margin-left:10px;" @click="loadModelList()">查询</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-table ref="multipleTable" :data="modelList" border highlight-current-row empty-text="暂无数据"
        v-loading="loadingModel" :header-cell-style="{background:'#f5f7fa'}" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center">
        </el-table-column>
        <el-table-column prop="name" label="名称" header-align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="createDate" label="创建日期" align="center" width="150">
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.state=='publish'">已发布</el-tag>
            <el-tag v-else>未发布</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="saveUserModel">保存</el-button>
        <el-button @click="modelDlgVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import MetaSelect from "../../components/meta-select";
  export default {
    name: "UserModelList",
    components: {MetaSelect},
    data() {
      return {
        isLoading: false,
        type: 'create',
        queryCondition: {
          name: '',
        },

        queryModelCondition: {
          name: '',
          projectType: '',
          userid: '',
          createTime: '',
          state: '',
        },
        pageNo: 1,
        companyList: [],
        companyMap: {},
        roleList: [],
        levelList: [],
        user: {},
        userList: [],
        dataCount: 1,
        loadingModel: false,
        isHeadOffice: false,

        modelList: [],
        modelDlgVisible: false,
        multipleSelection: [],

        userModel: [],
        userModelMap: {},
        actUserId: '', //当前活动（打开的）的用户id
      }
    },
    computed: {},
    created: function () {
      if (this.$route.params.type && this.$route.params.type.length > 0) {
        this.type = this.$route.params.type;
      }
      this.loadRoleData();
    },
    watch: {
      '$route'(to, from) {
        this.type = to.params.type;
      },
      type(val, oldVal) {
        this.loadUserList();
      }
    },
    mounted() {
      this.loadUserList();
    },
    methods: {
      loadUserList: function (pageNo) {
        this.isLoading = true;

        if (!pageNo) {
          pageNo = 1;
        } else {
          this.pageNo = pageNo;
        }
        this.queryCondition.pageNo = this.pageNo;

        this.$get("/user/data", this.queryCondition, (data) => {
          this.userList = data.data;
          this.dataCount = data.total;
        }, () => {
          this.isLoading = false;
        });
      },

      //根据用户加载 模型与用户的对应关系
      loadUserModel: function (userid) {
        this.$get("/model_user/list", {
          userId: userid,
        }, (data) => {
          this.userModel = data.data;

          var map = {};
          for (var i = 0; i < this.userModel.length; i++) {
            map[this.userModel[i].modelId] = this.userModel[i].modelId;
          }
          this.userModelMap = map;

        }, () => {});


        this.loadModelList();

      },

      //打开对应关系弹窗
      openEditDlg(item) {
        this.modelDlgVisible = true;
        this.loadingModel = true;

        this.loadUserModel(item.id);

        this.actUserId = item.id;
      },

      loadRoleData: function () {
        const message = this.$message;
        this.$get("/role/data", {}, (data) => {
          this.roleList = data.data;
        });
      },

      handleClickRow(row, column, event) {

      },

      loadCompanyList() {
        this.$get("/company/tree", {}, (data) => {
          var list = [];

          var map = {};
          for (var company of data.data) {
            map[company.id] = company;
            if (company.type != 'department') {
              list.push(company);
            }
            if (company.children && company.children.length > 0) {
              for (var subcompany of company.children) {
                map[subcompany.id] = subcompany;
                list.push(subcompany);
              }
            }
          }
          this.companyMap = map;
          // console.log(list)
          this.companyList = list;
        });
      },

      loadModelList: function () {

        this.loadingModel = true;
        this.$get("/model/data", {}, (response) => {
          this.modelList = response.data;
        }, () => {

          this.loadingModel = false;

          /*
                    //加载完模型数据，赋值勾选
                    if (Object.keys(this.userModel).length > 0) {
                      console.log('模型对应表', this.userModel)
                      this.modelList.forEach(element => {
                        if (element.id === this.userModelMap[element.id]) {

                          console.log('元素', element)
                          this.$refs.multipleTable.toggleRowSelection(this.modelList[1], true);
                        }
                      });

                    }

          */

          var setData = () => {
            this.userModel.forEach(row => {
              console.log('元素2', row)
              // 不能自己自定义对象来设置选中（原因如下分析），那我可以从列表中找到需要选中的那个对象，然后把它拿过来作为选中的项就可以了
              this.$refs.multipleTable.toggleRowSelection(this.modelList.find(item => {
                return row.modelId == item.id; // 注意这里寻找的字段要唯一，示例仅参考
              }), true);
            });
          }

          /*
          if (!this.$refs.multipleTable) {
            setTimeout(() => {
              setData()
            }, 500)
          } else {
            setData()
          }*/
          //设置延迟，否则勾选赋值不起作用   
          setTimeout(() => {
            setData()
          }, 500)

        });


      },

      handleSelectionChange(val) {
        this.multipleSelection = val;
        // console.log(this.multipleSelection);
      },

      //保存评价模型与用户的对应关系 
      saveUserModel() {
        const message = this.$message;
        this.userModel = [];
        for (var i = 0; i < this.multipleSelection.length; i++) {
          let item = {
            userId: this.actUserId,
            modelId: this.multipleSelection[i].id,
            state: ''
          };
          this.userModel.push(item);
        }

        this.$post("/model_user/save", this.userModel, () => {
          this.modelDlgVisible = false;
          message.success('创建成功！');
        });
      },

    },
  }
</script>